<template>
  <el-card class="box-card">
    <el-collapse v-loading="loading" v-model="activeNames" @change="queryList">
      <el-collapse-item v-for="(item, index) in items" :name="index" :key="item.id">
        <template slot="title">
          <span class="name">{{ item.name }}</span>
          <span style="float: right; margin-right: 20px">
            <span>正确率:  </span>
            <span class="num">{{ Math.floor(item.questCorrect * 100) }}%</span>
            <span>题量：</span>
            <span class="num">{{ item.num }} 道</span>
            <router-link :to="`/exercise/chapter/exercise/${examType}/${item.id}/all`"><el-button size="small">开始答题</el-button></router-link>
          </span>
        </template>
        <div style="background: #f0f2f5; padding: 20px">
          <p v-for="exercise in exercises[index]" :name="index" :key="exercise.id" style="border-bottom: 1px solid #eee; padding: 10px 0">
            <span class="name">{{ exercise.name }}</span>
            <span style="float: right; margin-right: 20px">
              <span>正确率:  </span>
              <span class="num">{{ Math.floor(exercise.questCorrect * 100) }}%</span>
              <span>题量：</span>
              <span class="num">{{ exercise.num }} 道</span>
              <router-link :to="`/exercise/chapter/exercise/${examType}/${item.id}/${exercise.id}`"><el-button size="small">开始答题</el-button></router-link>
            </span>
          </p>
        </div>
      </el-collapse-item>
    </el-collapse>
  </el-card>
</template>

<script>
import axios from 'axios'
import { EXERCISE_TYPE } from '@/constants/storage'
export default {
  data() {
    return {
      activeNames: [],
      items: [],
      exercises: [],
      examType: sessionStorage.getItem(EXERCISE_TYPE),
      loading: false
    }
  },
  mounted() {
    this.loading = true
    axios.get('/chapter/practice/homePage/' + this.examType).then(res => {
      this.loading = false
      if (res.success) {
        this.items = res.data
        this.exercises = new Array(res.data.length).fill([])
      }
    })
  },
  methods: {
    queryList(arr) {
      if (!arr.length) {
        return
      }
      const index = arr[ arr.length - 1]
      if (!this.exercises[index].length) {
        this.loading = true
        axios.get(`/chapter/practice/chapInfo/${this.items[index].id}/${this.examType}`).then(res => {
          this.loading = false
          if (res.success) {
            this.exercises[index] = res.data
            this.$forceUpdate()
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .box-card {
    margin: 20px;
  }
  .name {
    display: inline-block;
    margin-right: 20px;
  }
  .num {
    display: inline-block;
    margin-right: 10px;
    color: #F56C6C;
  }
</style>
